﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.Data;
using Telerik.WinControls.UI;
using QuanLyNhapXuat;
using System.IO;
using System.Text.RegularExpressions;
namespace Service.Presentation.WinForm
{
    public partial class frmNhapHang : Telerik.WinControls.UI.RadForm
    {
        static frmNhapHang doituong = null;
        public static frmNhapHang taodoituong()
        {
            if (doituong == null)
                doituong = new frmNhapHang();
            return doituong;
        }

        public frmNhapHang()
        {
            InitializeComponent();
        }
        //them service chi tiet nhap hang
        QuanLyNhapXuat.SR_ChiTietNhaPhang.WS_ChitietnhaphangSoapClient sr_ctnh = new QuanLyNhapXuat.SR_ChiTietNhaPhang.WS_ChitietnhaphangSoapClient();
        //them service khach hang
        QuanLyNhapXuat.RS_XuLiKhachHang.WS_KhachHangSoapClient sr_kh = new QuanLyNhapXuat.RS_XuLiKhachHang.WS_KhachHangSoapClient();
        //them service loai wash
        QuanLyNhapXuat.SR_LoaiWash.WS_LoaiWashSoapClient sr_lw = new QuanLyNhapXuat.SR_LoaiWash.WS_LoaiWashSoapClient();
        //them service mat hang
        QuanLyNhapXuat.SR_MatHang.WS_MatHangSoapClient sr_mh = new QuanLyNhapXuat.SR_MatHang.WS_MatHangSoapClient();
        //them service so nhap
        QuanLyNhapXuat.SR_SoNhap.WS_SoNhapSoapClient sr_sn = new QuanLyNhapXuat.SR_SoNhap.WS_SoNhapSoapClient();
        
        private bool them=false;
        private string masn;
        private DataSet ds_kh = new DataSet();
        private DataSet ds_mh = new DataSet();
        private DataSet ds_lw = new DataSet();
        private DataSet ds_ct = new DataSet();
        private int makh;
        private DateTime ngaynhap;

        public string MaNV_frmNhapHang;

        private void btn_DongForm_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_ThemMoi_Click(object sender, EventArgs e)
        {
            them = true;                        
            if (gridview_KetQua.AllowAddNewRow == false)
            {
                gridview_KetQua.AllowAddNewRow = true;
            }
            else
                gridview_KetQua.AllowAddNewRow = false;
            if (mcbb_KhachHang.Text.Length == 0 || mcbb_KhachHang.Text.Trim() == " ")
            {
                MessageBox.Show("Bạn hãy chọn thông tin khách hàng !!!");
                mcbb_KhachHang.Focus();
            }
            else
            {
                gbox_ChonMatHang.Enabled = true;
                numUD_SoLuong.Value = 1;
                meb_DonGia.Value = 0;
                mcbb_SanPham.SelectedIndex = -1;
                mcbb_KieuWash.SelectedIndex = -1;                
            }
        }

        private void btn_CapNhat_Click(object sender, EventArgs e)
        {
            if (them == true)
            {
                if (mcbb_SanPham.Text.Length == 0 || mcbb_SanPham.Text == " ")
                {
                    MessageBox.Show("Xin vui lòng nhập tên mặt hàng !!!");
                    mcbb_SanPham.Focus();
                }
                else if (mcbb_KieuWash.Text.Length == 0 || mcbb_KieuWash.Text == " ")
                {
                    MessageBox.Show("Xin vui lòng nhập tên kiểu wash !!!");
                    mcbb_KieuWash.Focus();
                }
                else if (numUD_SoLuong.Value == 0)
                {
                    MessageBox.Show("Xin vui lòng nhập số lượng mặt hàng !!!");
                    numUD_SoLuong.Focus();
                }
                else if (meb_DonGia.Text == "0")
                {
                    MessageBox.Show("Xin vui lòng nhập đơn giá !!!");
                    meb_DonGia.Focus();
                }
                else if (kiemtra == true)
                {
                    MessageBox.Show("Dữ liệu nhập của bạn có lỗi. Xin kiểm tra lại !!!");
                }
                else
                {
                    try
                    {
                        huy_binding();
                        //them vao so nhap
                        masn = xulyma();
                        makh = int.Parse(mcbb_KhachHang.SelectedValue.ToString());
                        ngaynhap = DateTP_NgayNhap.Value;
                        sr_sn.Them(masn, makh, MaNV_frmNhapHang, ngaynhap);
                        //them vao chi tiet nhap hang
                        mamh = mcbb_SanPham.SelectedValue.ToString();
                        string mawash = mcbb_KieuWash.SelectedValue.ToString();
                        int slnhap = int.Parse(numUD_SoLuong.Value.ToString());
                        int dongia = int.Parse(meb_DonGia.Text.Replace(",", ""));
                        sr_ctnh.them(masn, mamh, mawash, slnhap, dongia);
                        //load lai du lieu vao grid view
                        ds_ct.ReadXml(new StringReader(sr_ctnh.layds(makh)));
                        DataTable dt_them = ds_ct.Tables[0];
                        for (int i = 0; i < dt_them.Rows.Count; i++)
                        {
                            if (dt_them.Rows[i][5].ToString().Contains(".0000") == true)
                            {
                                dt_them.Rows[i][5] = dt_them.Rows[i][5].ToString().Replace(".0000", "");
                                dt_them.Rows[i]["NgayNhap"] = DateTime.Parse(dt_them.Rows[i]["NgayNhap"].ToString()).ToShortDateString();
                            }
                        }
                        gridview_KetQua.DataSource = dt_them;
                        them = false;
                        tao_binding();
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            else if (them == false)
            {
                try
                {
                    DataSet ds_ct_sua = new DataSet();
                    huy_binding();
                    makh = int.Parse(mcbb_KhachHang.SelectedValue.ToString());
                    mamh = mcbb_SanPham.SelectedValue.ToString();
                    string mawash = mcbb_KieuWash.SelectedValue.ToString();
                    int slnhap = int.Parse(numUD_SoLuong.Value.ToString());
                    int dongia = int.Parse(meb_DonGia.Text.Replace(",", ""));
                    sr_ctnh.sua(masn, mamh, mawash, slnhap, dongia);
                    ds_ct_sua.ReadXml(new StringReader(sr_ctnh.layds(makh)));
                    DataTable dt_cn = new DataTable();
                    dt_cn = ds_ct_sua.Tables[0];
                    for (int i = 0; i < dt_cn.Rows.Count; i++)
                    {
                        if (dt_cn.Rows[i][5].ToString().Contains(".0000") == true)
                        {
                            dt_cn.Rows[i][5] = dt_cn.Rows[i][5].ToString().Replace(".0000", "");
                            dt_cn.Rows[i]["NgayNhap"] = DateTime.Parse(dt_cn.Rows[i]["NgayNhap"].ToString()).ToShortDateString();
                        }
                    }
                    gridview_KetQua.DataSource = null;
                    gridview_KetQua.DataSource = dt_cn;
                    tao_binding();
                }
                catch (Exception ex)
                {
                }
            }
        }

        private void huy_binding()
        {
            mcbb_SanPham.DataBindings.Clear();
            mcbb_KieuWash.DataBindings.Clear();
            meb_DonGia.DataBindings.Clear();
            numUD_SoLuong.DataBindings.Clear();
        }

        private string xulyma()
        {
            DataSet tam = new DataSet();
            DateTime ngayhientai=DateTP_NgayNhap.Value;
            string chuoi="SN"+ngayhientai.Day.ToString("00")+ngayhientai.Month.ToString("00")+ngayhientai.Year.ToString();
            tam.ReadXml(new StringReader(sr_sn.SelectSQL("select top 1 masn from sonhap where masn like '"+chuoi+"%' order by masn desc")));
            string mamoi;
            if (tam.Tables.Count==0)
                mamoi = chuoi + "0001";
            else
            {
                string matam = tam.Tables[0].Rows[0][0].ToString();
                string kituso = matam.Substring(10, 5).ToString();
                int somoi = int.Parse(kituso) + 1;
                mamoi = chuoi + somoi.ToString("0000");
            }
            return mamoi;
        }
        //QuanLyNhapXuat.ServiceReference1.WS_MatHangSoapClient sr = new QuanLyNhapXuat.ServiceReference1.WS_MatHangSoapClient();
        private void frmNhapHang_Load(object sender, EventArgs e)
        {
            //load du lieu cua khach hang
            Load_DS_KhachHang();           

            //load du lieu cua mat hang
            try
            {
                ds_mh.ReadXml(new StringReader(sr_mh.layds()));
                //ds_mh.ReadXml(new StringReader(sr.layds()));
                mcbb_SanPham.DataSource = ds_mh.Tables[0];
                mcbb_SanPham.DisplayMember = "tenmh";
                mcbb_SanPham.ValueMember = "mamh";
                mcbb_SanPham.SelectedIndex = -1;
                FilterDescriptor des_mh = new FilterDescriptor(this.mcbb_SanPham.DisplayMember, FilterOperator.StartsWith, string.Empty);
                mcbb_SanPham.EditorControl.FilterDescriptors.Add(des_mh);                
            }
            catch (Exception ex)
            {
            }
            //load du lieu cua loai wash
            try
            {
                ds_lw.ReadXml(new StringReader(sr_lw.layds()));
                mcbb_KieuWash.DataSource = ds_lw.Tables[0];
                mcbb_KieuWash.DisplayMember = "tenwash";
                mcbb_KieuWash.ValueMember = "mawash";
                mcbb_KieuWash.SelectedIndex = -1;
                FilterDescriptor des_lw = new FilterDescriptor(this.mcbb_KieuWash.DisplayMember, FilterOperator.StartsWith, string.Empty);
                mcbb_KieuWash.EditorControl.FilterDescriptors.Add(des_lw);

            }
            catch (Exception ex)
            {
            }
            DateTP_NgayNhap.Value = DateTime.Today;
            //them data binding
            tao_binding();
            //Xoa DSSoNhap Theo Khach Hang
            gridview_KetQua.DataSource = null;
            numUD_SoLuong.Value = 1;
            meb_DonGia.Value = 0;
        }

        private void Load_DS_KhachHang()
        {            
            try
            {
                ds_kh.Clear();
                //Chinh do dai cua cac cot trong muiltcombobox
                RadMultiColumnComboBoxElement multiColumnComboElement = this.mcbb_KhachHang.MultiColumnComboBoxElement;
                multiColumnComboElement.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multiColumnComboElement.DropDownMinSize = new Size(300, 200);

                ds_kh.ReadXml(new StringReader(sr_kh.layds()));
                mcbb_KhachHang.DataSource = ds_kh.Tables[0];
                mcbb_KhachHang.DisplayMember = "tenkh";
                mcbb_KhachHang.ValueMember = "makh";
                mcbb_KhachHang.SelectedIndex = -1;
                FilterDescriptor des_kh = new FilterDescriptor(this.mcbb_KhachHang.DisplayMember, FilterOperator.StartsWith, string.Empty);
                mcbb_KhachHang.EditorControl.FilterDescriptors.Add(des_kh);                
            }
            catch (Exception ex){}
        }

        private void tao_binding()
        {
            try
            {
                if (gridview_KetQua.Rows.Count > 0)
                {
                    huy_binding();
                    mcbb_SanPham.DataBindings.Add("Text", gridview_KetQua.DataSource, "tenmh");
                    mcbb_KieuWash.DataBindings.Add("Text", gridview_KetQua.DataSource, "tenwash");
                    numUD_SoLuong.DataBindings.Add("Text", gridview_KetQua.DataSource, "soluongnhap");
                    meb_DonGia.DataBindings.Add("Text", gridview_KetQua.DataSource, "dongianhap");
                }
            }
            catch (Exception ex)
            {
            }
        }
        
        private void mcbb_KhachHang_SelectedIndexChanged(object sender, EventArgs e)
        {           
            if (mcbb_KhachHang.SelectedIndex != -1)
            {
                huy_binding();
                DataSet tam = new DataSet();
                string makh = mcbb_KhachHang.SelectedValue.ToString();
                tam.ReadXml(new StringReader(sr_ctnh.selectquery("select CHITIETNHAPHANG.masn,tenmh,tenwash,ngaynhap,soluongnhap,dongianhap from CHITIETNHAPHANG,MATHANG,LOAIWASH,SONHAP where CHITIETNHAPHANG.MAMH=MATHANG.MAMH and CHITIETNHAPHANG.mawash=LOAIWASH.MAWASH and CHITIETNHAPHANG.MASN=SONHAP.MASN and MAKH='"+makh+"'")));
                if (tam.Tables.Count > 0)
                {
                    DataTable dt = new DataTable();
                    dt = tam.Tables[0];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i][5].ToString().Contains(".0000") == true)
                        {
                            dt.Rows[i][5] = dt.Rows[i][5].ToString().Replace(".0000", "");
                            dt.Rows[i]["NgayNhap"] = DateTime.Parse(dt.Rows[i]["NgayNhap"].ToString()).ToShortDateString();
                        }
                    }
                    gridview_KetQua.DataSource = dt;
                    tao_binding();
                }
                else
                    gridview_KetQua.DataSource = null;
            }
        }

        private void gridview_KetQua_CurrentRowChanged(object sender, CurrentRowChangedEventArgs e)
        {
            try
            {
                if (gridview_KetQua.RowCount != -1)
                {
                    them = false;
                    DataSet tam = new DataSet();
                    DataSet tm_mamh = new DataSet();
                    tenmh = e.CurrentRow.Cells["MatHang"].Value.ToString();
                    tm_mamh.ReadXml(new StringReader(sr_mh.selectquery("select mamh from mathang where tenmh=N'" + tenmh + "'")));
                    mamh = tm_mamh.Tables[0].Rows[0][0].ToString();
                    string makh = mcbb_KhachHang.SelectedValue.ToString();
                    tam.ReadXml(new StringReader(sr_ctnh.selectquery("select chitietnhaphang.masn from CHITIETNHAPHANG,SONHAP where CHITIETNHAPHANG.MASN=SONHAP.MASN and MAMH='" + mamh + "'" + "and MAKH='" + makh + "'")));
                    masn = tam.Tables[0].Rows[0][0].ToString();
                }
            }
            catch (Exception ex)
            {
            }
        }
        string tenmh;
        string mamh;
        private void btn_XoaHang_Click(object sender, EventArgs e)
        {
            try
            {
                makh = int.Parse(mcbb_KhachHang.SelectedValue.ToString());
                sr_ctnh.xoa(masn, mamh);
                gridview_KetQua.CurrentRow.Delete();
            }
            catch (Exception ex)
            {
            }
        }

        private void mcbb_KhachHang_Leave(object sender, EventArgs e)
        {
            error.Clear();
            if (mcbb_KhachHang.Text.Trim() != "")
            {             
                Regex rg = new Regex(@"^[^0-9]\w[^0-9]+$");
                Match m = rg.Match(mcbb_KhachHang.Text);
                if (mcbb_KhachHang.Text.Length == 0 || mcbb_KhachHang.Text == " ")
                    error.SetError(mcbb_KhachHang, "Xin vui lòng nhập tên khách hàng !!!");
                else if (!m.Success)
                {
                    error.SetError(mcbb_KhachHang, "Tên khách hàng chỉ được nhập chữ !!!");
                    mcbb_KhachHang.Focus();
                }
            }
            
        }

        private void meb_DonGia_TextChanged(object sender, EventArgs e)
        {            
        }

        private void btn_ThemNhanh_Click(object sender, EventArgs e)
        {
            frm_KhachHang khachhang = frm_KhachHang.TaoDoiTuong();
            khachhang.ShowDialog();
            //Load lai DS Khach Hang vua them vao
            Load_DS_KhachHang();            
            gridview_KetQua.DataSource = null;
            if(khachhang.MaKH_MoiThem != 0)
                mcbb_KhachHang.EditorControl.Rows[khachhang.MaKH_MoiThem - 1].IsCurrent = true;
        }

        private void numUD_SoLuong_Leave(object sender, EventArgs e)
        {
            error.Clear();
            decimal soluong_tam = numUD_SoLuong.Value;
            if (soluong_tam > 1000)
            {
                error.SetError(numUD_SoLuong, "Số lượng nhập không quá 1000 !!!");
                numUD_SoLuong.Maximum = numUD_SoLuong.Value;
                numUD_SoLuong.Focus();
                kiemtra = true;
            }
            if (soluong_tam < 1)
            {
                error.SetError(numUD_SoLuong, "Số lượng nhập không được nhỏ hơn 1 !!!");
                numUD_SoLuong.Focus();
                kiemtra = true;
            }
        }
        bool kiemtra = false;
        private void meb_DonGia_Leave(object sender, EventArgs e)
        {
            error.Clear();
            string dongia_tam = meb_DonGia.Value.ToString();
            decimal bien_SS =decimal.Parse(dongia_tam.ToString());
            if (bien_SS > 20000)
            {
                kiemtra = true;
                error.SetError(meb_DonGia,"Đơn giá không quá 20000 VND !!!");
                meb_DonGia.Focus();
            }
        }     
    }
}
